package com.xf.system.utils.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiefengf
 */
@Slf4j
public class ImportExcelListener<T> extends AnalysisEventListener<T> {

    /**
     * 导入表头
     */
    private final List<String> importHead = new ArrayList<>();

    /**
     * 导入数据列表
     */
    private final List<T> list = new ArrayList<>();

    public List<String> getImportHead() {
        return importHead;
    }

    public List<T> getList() {
        return list;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        //获取当前读取的行数
        Integer currentRowNum = analysisContext.readRowHolder().getRowIndex();
        //获取导入表头，默认第一行为表头
        if(currentRowNum == 0){
            try {
                Map<String,Object> m = objToMap(t);
                for (Object v : m.values()) {
                    importHead.add(String.valueOf(v).trim());
                }
            } catch (Exception e) {
                log.error("invoke error:"+e.getMessage());
            }
        }else{
            list.add(t);
        }
    }

    /**
     * 把接受的对象的Object的属性转换为Map
     * @param obj 对象
     * @return Map
     * @throws Exception
     */
    public Map<String,Object> objToMap(T obj) throws Exception{
        Map<String,Object> map = new LinkedHashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field field : fields){
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("Excel读取完毕！！！");
    }
}
